<template>
  <div class="zh-edit-platform-user">
    <nav-header>
      <template slot="menuBefore">
        <li><router-link to="/user/user/platform-user" tag="a">平台用户管理</router-link></li>
        <li class="gap">&gt;</li>
      </template>
      <li>修改用户信息</li>
    </nav-header>

    <div class="zh-edit-from" v-loading="loading.status" :element-loading-text="loading.txt">
      <el-form :model="editForm" status-icon ref="editForm" :rules="rules" label-position="left" label-width="100px">
        <p class="form-title">基本信息</p>
        <el-form-item label="用户名" prop="name" class="edit-from-width">
          <el-input v-model.trim="editForm.name" placeholder="请输入真实姓名(20个字符内)" autocomplete="off"
            :maxlength="parseInt(20)" clearable>
          </el-input>
        </el-form-item>
        <el-form-item label="人脸照片" prop="faceImg" class="edit-from-width">
          <upload-img :options="uploadOptions" :picture="editForm.face_path" @imgListen="getImg"></upload-img>
        </el-form-item>
        <el-form-item label="性别">
          <el-radio v-model="editForm.sex" label="1">男</el-radio>
          <el-radio v-model="editForm.sex" label="2">女</el-radio>
        </el-form-item>
        <el-form-item label="组织架构" class="edit-from-width">
          <el-select v-model="editForm.org_id" filterable placeholder="请填写组织架构" :disabled="true">
            <el-option v-for="val in orgData" :key="val.id" :label="val.name" :value="val.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="角色权限">
          <el-checkbox-group v-model="editForm.role_id" @change="addFormRoleChange">
            <template v-for="item in roleData">
              <el-checkbox :label="item.base_id === 0 ? item.id : item.base_id" :key="item.id" border>{{ item.name
                }}</el-checkbox>
            </template>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="登录账号" prop="number" class="edit-from-width">
          <el-input v-model="editForm.number" placeholder="登录时要想到的帐号" autocomplete="off" :maxlength="parseInt(16)"
            :disabled="true">
          </el-input>
        </el-form-item>
        <el-form-item label="登录密码" prop="password" class="edit-from-width">
          <el-input v-model="editForm.password" type="password" placeholder="默认密码为Admin@1993；输入可更新密码"
            :maxlength="parseInt(16)" clearable show-password>
          </el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="newpassword" class="edit-from-width">
          <el-input v-model="editForm.newpassword" type="password" placeholder="再次输入新密码" :maxlength="parseInt(16)"
            clearable show-password>
          </el-input>
        </el-form-item>
        <el-form-item v-if="isShowSubjectFlag" label="任教科目" class="edit-from-width">
          <el-select v-model="editForm.subject_id" filterable placeholder="选择任教科目">
            <el-option v-for="val in subjectData" :key="val.id" :label="val.name" :value="val.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="$g.user_id === $g.GLOBE_ADMIN_ID" prop="user_time" class="user-time" label="有效时间">
          <el-radio-group v-model="user_time">
            <el-radio label="1">永久有效</el-radio>
            <el-radio label="2">
              <div>
                <span>临时用户</span>
                <span style="margin-left: 20px;">使用截止时间：
                  <el-date-picker :picker-options="pickerOptions" v-model="short_time" type="datetime"
                    placeholder="选择日期时间" value-format="yyyy-MM-dd HH:mm:ss">
                  </el-date-picker>
                </span>
              </div>
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <template v-if="isParent">
          <p class="form-title">角色设定（家长）</p>
          <div class="children-box">
            <el-tabs v-model="parentEditTabsValue" type="card" editable @edit="parentHandleTabsEdit"
              :class="editForm.parent_bind.length < 10 ? 'tabs-head-title' : ''">
              <el-tab-pane v-for="(item, index) in editForm.parent_bind"
                :label="item.childrenName ? item.childrenName : '子女' + (index + 1)" :name="item.name" :key="item.name">
                <template>
                  <el-form-item label="子女账号" class="edit-from-width">
                    <el-input v-model="item.student_number" placeholder="你家小孩的登录账号" @blur="check_user(index, 1)"
                      autocomplete="off" :maxlength="parseInt(16)" clearable @clear="childClear(index)">
                    </el-input>
                  </el-form-item>
                  <el-form-item label="子女密码" class="edit-from-width">
                    <el-input v-model="item.student_password" type="password" placeholder="你家小孩的账号密码"
                      @blur="check_user(index, 0)" autocomplete="off" :maxlength="parseInt(16)" clearable>
                    </el-input>
                  </el-form-item>
                </template>
              </el-tab-pane>
            </el-tabs>
          </div>
        </template>

        <template v-if="isTeacher">
          <p class="form-title">角色设定（教师）</p>
          <div class="character-box">
            <el-tabs v-model="teachEditTabsValue" type="card" editable @edit="teachHandleTabsEdit"
              :class="(teacher_bind.length > 0 && teacher_bind[0].teacher_class_id == '' && teacher_bind.length == 1) ? 'tabs-close' : ''">
              <el-tab-pane v-for="(item, index) in teacher_bind"
                :label="item.teacher_class_id.length > 0 ? changeTeachName(item.teacher_class_id) : '班级' + (index + 1)"
                :name="item.name" :key="item.name">
                <template>
                  <el-form-item label="任教班级" class="edit-from-width">
                    <el-cascader :options="teachOptions" @change="teachSelect" v-model="item.teacher_class_id"
                      placeholder="选择任教班级" :disabled="setAbled(item.teacher_class_id)" clearable>
                    </el-cascader>
                  </el-form-item>
                  <el-form-item label="班级岗位" class="edit-from-width">
                    <el-select v-model="item.teacher_job_id" multiple filterable placeholder="选择教师岗位">
                      <el-option v-for="val in teachPostData" :key="val.job_id" :label="val.job_name"
                        :value="val.job_id">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </template>
              </el-tab-pane>
            </el-tabs>
          </div>
        </template>

        <template v-if="isStudent">
          <p class="form-title">角色设定（学生）</p>
          <el-form-item label="绑定班级" class="edit-from-width">
            <el-cascader :options="studentOptions" @change="studentSelect" v-model="studentSelectOptions"
              placeholder="暂不绑定" clearable></el-cascader>
          </el-form-item>
          <el-form-item label="岗位设置" class="edit-from-width">
            <el-select v-model="student_job_id" filterable placeholder="暂不指定" clearable>
              <el-option v-for="item in postData" :key="item.job_id" :label="item.job_name" :value="item.job_id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="学生状态" class="edit-from-width">
            <el-select v-model="study_status" filterable placeholder="暂不指定" clearable>
              <el-option label="正常" value="1"></el-option>
              <el-option label="劝退" value="2"></el-option>
              <el-option label="休学" value="3"></el-option>
              <el-option label="转出" value="4"></el-option>
              <el-option label="开除学籍" value="5"></el-option>
              <el-option label="已毕业" value="6" disabled></el-option>
            </el-select>
          </el-form-item>
        </template>

        <p class="form-title">联系信息</p>
        <el-form-item label="用户邮箱" prop="email" class="edit-from-width"
          :rules="[{ type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }]">
          <el-input v-model="editForm.email" placeholder="请输入绑定邮箱" autocomplete="off" :maxlength="parseInt(20)"
            clearable>
          </el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="telphone" class="edit-from-width"
          :rules="[{ pattern: /^[1][3,4,5,6,7,8,9][0-9]{9}$|^(([0\+]\d{2,3}-)?(0\d{2,3})-)(\d{7,8})(-(\d{3,}))?$/, message: '手机号码格式错误', trigger: ['blur', 'change'] }]">
          <el-input v-model="editForm.telphone" placeholder="请输入11位手机号" autocomplete="off" :maxlength="parseInt(11)"
            clearable>
          </el-input>
        </el-form-item>
        <p class="form-title">安全验证</p>
        <el-form-item label="验证密码" prop="user_password" class="edit-from-width">
          <el-input type="password" v-model="editForm.user_password" placeholder="输入当前密码进行安全认证" autocomplete="off"
            :maxlength="parseInt(16)" clearable show-password>
          </el-input>
        </el-form-item>
      </el-form>
      <div class="submit-button">
        <el-button @click="cancel()">取消</el-button>
        <el-button type="primary" plain @click="resetForm()">重置</el-button>
        <el-button type="primary" @click="submitForm()">保存</el-button>

      </div>
    </div>
  </div>
</template>

<script>
import uploadImg from '../../common/uploader-image.vue'
import { longTimeMessage } from './../../../tools/tool';

export default {
  components: {
    uploadImg
  },
  data() {
    return {
      isManageFlag: false,
      dataMag: [],
      baseIDarr: [],
      parentTabIndex: 1, // tab 数量
      teachTabIndex: 1,
      parentEditTabsValue: '1', // 家长可编辑的标签值
      teachEditTabsValue: '1',
      initFuncNum: 2, // 初始化函数的数量
      initFuncNumFinal: 0, // 初始化函数
      isStudent: false,  // 角色权限是否为学生
      isTeacher: false,   //角色权限是否为教师
      isParent: false,    //角色权限是否为家长
      isShowSubjectFlag: false, // 是否显示任教科目
      parentFlag: [], // 子女账号是否错误
      roleData: [], /* 角色权限 */
      subjectData: [],
      teachClassData: [],
      teachPostData: [],
      classData: [],
      postData: [],
      orgData: [],
      baseTeacherClass: [], // 教师绑定班级列表
      roleParam: {
        type: 1,
      },
      loading: {
        status: false,
        txt: '获取数据...',
      },
      infoParam: {
        id: this.$route.params.id,
        level: 2
      },
      orgParam: {
        data_type: 'manage_tree',
        status: [1, 2],
      },
      user_time: '1',
      short_time: '',
      pickerOptions: {
        disabledDate: (time) => {
          return time.getTime() < parseInt(Date.now() - 8.64e7);
        }
      },
      editForm: {
        id: this.$route.params.id,
        name: '',
        sex: '1',
        org_id: '',
        number: '',
        subject_id: '',
        student_bind: [],
        password: undefined,
        newpassword: undefined,
        email: '',
        telphone: '',
        user_password: '',
        role_id: [],
        parent_bind: [],
        teacher_bind: [],
        children: [],
        use_start_time: '',
        use_end_time: '',
        face_path: null
      },
      teacher_bind: [],
      student_job_id: '',
      study_status: null, // 记录学生学习状态
      studentSelectOptions: [],
      rules: {
        name: [
          { validator: this.validateContent, trigger: 'blur', required: true }
        ],
        number: [
          { pattern: this.rules.account.reg, message: this.rules.account.msg, trigger: 'blur' },
          { validator: this.validateAccounts, trigger: 'blur', required: true }
        ],
        password: [
          { validator: this.validatePwdRole, trigger: "blur" }
        ],
        newpassword: [
          { validator: this.validateCheckPass, trigger: 'blur' }
        ],
        subject_id: [
          { validator: this.checkChange, trigger: 'change', required: true }
        ],
        user_password: [
          { validator: this.validateNumbers, trigger: 'blur', required: true }
        ],
        org_id: [
          { validator: this.checkChange, trigger: 'change', required: true }
        ],
        user_time: [
          { validator: this.valUserTime, trigger: 'change' },
        ]
      },
      studentOptions: [],
      teachOptions: [],
      childrenAccount: [], // 家长角色--已验证的子女账号
      // 单极数据
      editableTabsValue: '0',
      selectedOrgOptions: [],
      orgDataProps: {
        value: 'id',
        label: 'name',
      },
      messageObj: {},
      bindTeach: [], // 缓存路由
      longSocket: null,
      uploadOptions: {
        target: this.BASE_URL + '/api/resource/res_upload',
        testChunks: false,
        headers: { Authorization: `Bearer ` + this.$g.access_token },
      },
    }
  },
  created() {
    this.getOrgData();
    this.getRoleData();
    this.getSubjectData();
    this.websocketInit();
  },
  watch: {
    initFuncNumFinal: {
      handler(newVal, oldVal) {
        if (parseInt(newVal) === this.initFuncNum) {
          this.getInfo();
        }
      },
      deep: true
    },
    selectedOrgOptions: {
      handler(newVal, oldVal) {
        this.editForm.org_id = newVal[newVal.length - 1];
      },
      deep: true
    },
    'editForm.role_id'(newVal, oldVal) {
      if (!is_empty(this.baseTeacherClass)) {
        this.bindTeach = oldVal;
      }
    }
  },
  beforeDestroy() {
    if (this.longSocket) {
      this.longSocket.close();
    }
  },
  methods: {
    getImg(mess) {
      this.editForm.face_path = mess.file_path;
      if (mess.file_path) {
        let success = (res => {
          // 因为后端false的时候是[],所以必须==true判断
          if (res.data == true) {
            this.editForm.face_path = mess.file_path;
            this.$message.success('上传成功');
          }

        })
        let fail = (res => {
          this.editForm.face_path = null;
          this.$message.error(res.msg);
        })

        this.$ajax.get('/api/ainew/checkFace', { params: { path: mess.file_path }, func: { success, fail } })
      }
    },
    /**
     * 设置班级是否可更改
     * @param {Array} arr 班级
     */
    setAbled(arr) {
      let flag = false;

      !is_empty(this.baseTeacherClass) && this.baseTeacherClass.forEach(item => {
        if (item.id === arr[2]) {
          flag = true;
        }
      })

      if (flag) {
        return true;
      } else {
        return false;
      }
    },
    valUserTime(rule, value, callback) {
      if (this.user_time === '2' && !this.short_time) {
        callback(new Error('请输入使用截止时间'));
      } else {
        callback();
      }
    },
    // 单级
    handleTabsEdit(targetName, action) {
      if (Object.is(action, 'add')) {
        this.editForm.children.push(
          {
            zinumber: '',
            zipassword: '',
          }
        )
      }
      if (Object.is(action, 'remove')) {
        if (Object.is(this.editForm.children.length, 1)) {
          return;
        }
        this.editForm.children.splice(targetName, 1);
      }
    },
    changeTeachName(val) {
      let name = '';

      this.teachOptions.forEach(item => {
        if (val[0] && item.value == val[0]) {
          name = item.label;

          if (val[1]) {
            item.children.forEach(res => {
              if (val[1] == res.value) {
                name = item.label + '/' + res.label;

                if (val[2]) {
                  res.children.forEach(data => {
                    if (data.value == val[2]) {
                      name = item.label + '/' + res.label + '/' + data.label;
                    }
                  })
                }
              }
            })
          }
        }
      })

      return name;
    },
    /**
     * 清空子女账号或子女账号错误时清空密码
     * 2019-5-5 清空子女账号 student_flag 为 false
     */
    childClear(index) {
      let data = this.editForm.parent_bind[index];
      if (data.student_number == '') {
        this.editForm.parent_bind[index].student_password = '';
        this.editForm.parent_bind[index].student_flag = null;
        this.editForm.parent_bind[index].childrenName = '';
      }
    },
    check_user(index, num) {
      let data = this.editForm.parent_bind[index];
      this.dataMag = data
      if (num === 1 && this.childrenAccount.indexOf(data.student_number) < 0) {
        this.editForm.parent_bind[index].student_flag = null;
      }

      if (data.student_number != '' && data.student_password != '') {
        let params = {
          number: data.student_number,
          password: data.student_password
        }
        let success = (res => {
          this.$message.success('子女账号密码正确');
          this.editForm.parent_bind[index].childrenName = res.data.name;
        });
        let fail = (res => {
          this.$message.error(res.msg);
          this.editForm.parent_bind[index].student_password = '';
          this.editForm.parent_bind[index].student_flag = null;
        })
        this.$ajax.get('api/user/check_user', { params: params, func: { success: success, fail: fail } })
      }
    },
    isShowSubject() {
      this.isShowSubjectFlag = this.editForm.role_id.indexOf(this.$g.TEACHER_ROLE_ID) > -1;
    },
    teachSelect(val) {
      // 动态改变标签的名字
      let len = this.teachEditTabsValue;

      this.teachPostData = [];
      this.teacher_bind.forEach(item => {
        if (item.name == len) {
          item.teacher_job_id = [];
        }
      })

      if (val.length === 3) {
        let flag = false;

        this.teacher_bind.forEach(item => {
          if (item.name == len) {
            item.teacher_class_id = [];
          }
        })

        this.teacher_bind.forEach(item => {
          if (val[2] === item.teacher_class_id[2]) {
            flag = true;
          }
        })

        if (flag) {
          this.teacher_bind.forEach(item => {
            if (item.name == len) {
              item.teacher_class_id = [];
            }
          })

          this.$message.warning('不可以重复选中任教班级');
        } else {
          this.teacher_bind.forEach(item => {
            if (item.name == len) {
              item.teacher_class_id = val;
            }
          })

          this.getTeachPost(val[2])
        }
      }

      if (val.length < 3) {
        this.teacher_bind.forEach(item => {
          if (item.name == len) {
            item.teacher_class_id = [];
          }
        })
      }
    },
    // 获取教师岗位信息
    getTeachPost(classId) {
      let params = {
        class_id: classId,
      }
      const success = res => {
        this.teachPostData = res.data.teacher_job;
      }

      this.$ajax.get('api/user/class_job_data', { params: params, func: { success: success } })
    },
    // 获取学生岗位信息
    studentSelect(val) {
      this.postData = [];
      this.student_job_id = '';

      if (val.length === 3 && val[2] != undefined) {
        let params = {
          class_id: val[2],
        }
        const success = res => {
          this.postData = res.data.student_job;
        }

        this.$ajax.get('api/user/class_job_data', { params: params, func: { success: success } })
      }

      if (this.studentSelectOptions.length < 3) {
        this.studentSelectOptions = [];
      }
    },
    // 从组织架构获取班级信息
    studentItem() {
      // console.log(this.studentOptions,189)
      let data = this.studentData[0].children;
      if (data) {
        data.forEach((val, index) => {
          let data2 = val.children;

          if (!is_empty(data2)) {
            this.studentOptions.push({
              value: val.id,
              label: val.name,
              children: []
            })

            data2.forEach((res, index2) => {
              let data3 = res.children;

              if (!is_empty(data3)) {
                this.studentOptions[index].children.push({
                  value: res.id,
                  label: res.name,
                  children: []
                })

                data3.forEach((tex, index3) => {
                  this.studentOptions[index].children[index2].children.push({
                    value: tex.id,
                    label: tex.name,
                  })
                })
              } else {
                this.studentOptions[index].children.push({
                  value: res.id,
                  label: res.name,
                })
              }
            })
          } else {
            this.studentOptions.push({
              value: val.id,
              label: val.name,
            })
          }
        })
      }
      this.teachOptions = deep_clone(this.studentOptions);
      // console.log(this.studentOptions, '教师')
    },
    parentHandleTabsEdit(targetName, action) {
      if (action === 'add') {
        let newTabName = ++this.parentTabIndex + '';
        this.editForm.parent_bind.push({
          name: newTabName,
          student_number: '',
          student_password: '',
          childrenName: ''
        });
        this.parentEditTabsValue = newTabName;
      }

      if (this.editForm.parent_bind.length > 1) {
        if (action === 'remove') {
          let tabs = this.editForm.parent_bind;
          let activeName = this.parentEditTabsValue;
          if (activeName === targetName) {
            tabs.forEach((tab, index) => {
              if (tab.name === targetName) {
                let nextTab = tabs[index + 1] || tabs[index - 1];
                if (nextTab) {
                  activeName = nextTab.name;
                }
              }
            });
          }

          this.parentEditTabsValue = activeName;
          this.editForm.parent_bind = tabs.filter(tab => tab.name !== targetName);
        }
      } else {
        if (action === 'remove') {
          this.editForm.parent_bind[0].student_flag = null;
          this.editForm.parent_bind[0].student_number = '';
          this.editForm.parent_bind[0].student_password = '';
          this.editForm.parent_bind[0].childrenName = '';
        }
      }
    },
    teachHandleTabsEdit(targetName, action) {
      if (action === 'add') {
        let newTabName = ++this.teachTabIndex + '';
        this.teacher_bind.push({
          name: newTabName,
          teacher_class_id: [],
          teacher_job_id: []
        });
        this.teachEditTabsValue = newTabName;
      }

      if (action === 'remove') {
        let flag = true;
        let className = '';

        !is_empty(this.baseTeacherClass) && this.baseTeacherClass.forEach((item, inx1) => {
          className += inx1 !== 0 ? ` 和 【${item.rename}】` : '' + `【${item.rename}】`;
        })

        if (this.teacher_bind.length > 1) {
          let arr = this.teacher_bind.filter(item => item.name == targetName);
          !is_empty(this.baseTeacherClass) && this.baseTeacherClass.forEach(item => {
            if (item.id === arr[0].teacher_class_id[2]) {
              flag = false;
            }
          })

          if (flag) {
            flag = true;

            let tabs = this.teacher_bind;
            let activeName = this.teachEditTabsValue;
            if (activeName === targetName) {
              tabs.forEach((tab, index) => {
                if (tab.name === targetName) {
                  let nextTab = tabs[index + 1] || tabs[index - 1];
                  if (nextTab) {
                    activeName = nextTab.name;
                  }
                }
              });
            }

            this.teachEditTabsValue = activeName;
            this.teacher_bind = tabs.filter(tab => tab.name !== targetName);
          } else {
            this.$message.warning(`由于${this.editForm.name}是${className}的班主任，如要取消该用户教师身份，请去班级管理中更改绑定班级的班主任`);
          }
        } else {
          !is_empty(this.baseTeacherClass) && this.baseTeacherClass.forEach(item => {
            if (item.id === this.teacher_bind[0].teacher_class_id[2]) {
              flag = false;
            }
          })

          if (flag) {
            flag = true;
            this.teacher_bind[0].teacher_job_id = [];
            this.teacher_bind[0].teacher_class_id = [];
          } else {
            this.$message.warning(`由于${this.editForm.name}是${className}的班主任，如要取消该用户教师身份，请去班级管理中更改绑定班级的班主任`);
          }
        }
      }
    },
    /**
     * 获取页面信息
     * 2019-5-5 产品要求单级、多级页面合并，不再区分单级、多级
     */
    getInfo() {
      this.loading.status = true;
      this.isStudent = false;
      this.isTeacher = false;
      this.isParent = false;

      let fail = (data => {
        this.loading.status = false;
        this.$message.error(data.msg);
      })
      let success = (res => {
        let data = {
          data: res.data[0]
        }
        this.loading.status = false;
        this.baseTeacherClass = data.data.base_teacher_class;
        this.editForm.name = data.data.name;
        this.editForm.sex = data.data.sex.toString();
        this.editForm.face_path = data.data.face_path



        // // 角色权限：checkbox绑定的是base_id
        let idArr = [];
        let roleIds = data.data.rolebase.map(item => item.role_id);
        idArr = this.roleData
          .filter(item => roleIds.includes(item.id))
          .map(item => item.id);
        this.editForm.role_id = idArr;
        this.editForm.subject_id = parseInt(data.data.subject_id) === 0 ? '' : data.data.subject_id;
        this.studentSelectOptions = data.data.student_org ? [data.data.student_org.study_org_id, data.data.student_org.grade_id, data.data.student_org.class_id] : [];
        this.editForm.number = data.data.number;
        // this.editForm.use_end_time = data.data.use_end_time;
        // this.editForm.use_start_time = data.data.use_start_time;
        this.editForm.email = data.data.email;
        this.editForm.telphone = data.data.telphone;
        this.editForm.parent_bind = [];
        this.teacher_bind = [];

        if (data.data.use_start_time == data.data.use_end_time) {
          this.user_time = '1';
        } else {
          this.user_time = '2';
          this.short_time = data.data.use_end_time;
        }

        // if (this.user_multistage === false) {
        //     this.editForm.org_id =  data.data.org_id;
        //     this.selectedOrgOptions = data.data.org_ids; //组织架构
        // }

        if (this.studentSelectOptions.length == 3) {
          this.studentSelect(this.studentSelectOptions);
        }

        if (parseInt(data.data.is_student) === 1) {
          this.isStudent = true;
          // console.log(data.data, 'pppppppppppppppppp')
          if (data.data.student_org) {
            this.editForm.student_bind.push({
              student_class_id: [data.data.student_org.study_org_id, data.data.student_org.grade_id, data.data.student_org.class_id],
              student_job_id: data.data.student_org.student_job_id
            })

            this.student_job_id = data.data.student_org.student_job_id;
          }

          this.study_status = data.data.study_status + '';
        }

        if (parseInt(data.data.is_teacher) === 1) {
          this.isTeacher = true;
          this.isShowSubjectFlag = true;
          let result = data.data.teacher_org;
          // console.log(data.data, 'pppppppppppppppppp')
          if (result && result.length > 0) {
            for (let i = 0; i < result.length; i++) {
              this.teacher_bind.push({
                name: i + 1 + '',
                teacher_class_id: [result[i].study_org_id, result[i].grade_id, result[i].class_id],
                teacher_job_id: result[i].teacher_job_id
              })
              this.getTeachPost(result[i].class_id);
            }
          } else {
            this.teacher_bind = [
              {
                name: '1',
                teacher_class_id: [],
                teacher_job_id: []
              }
            ]
          }
        } else {
          this.teacher_bind = [
            {
              name: '1',
              teacher_class_id: [],
              teacher_job_id: []
            }
          ]
        }

        // if( this.user_multistage === false && parseInt(data.data.is_parent) === 1 ){
        //     this.isParent = true;

        //     if(data.data.children.length > 0) {
        //         this.editForm.children = [];
        //         for(  var i = 0 ;  i < data.data.children.length ; i ++ ){
        //             this.editForm.children.push({zinumber:data.data.children[i],zipassword: ''})
        //         }
        //     } else {
        //         this.editForm.children = [{
        //             zinumber: '',
        //             zipassword: ''
        //         }]
        //     }
        // }

        // if( this.user_multistage === true && parseInt(data.data.is_parent) === 1 ){
        if (parseInt(data.data.is_parent) === 1) {
          this.isParent = true;
          let childrenInfo = data.data.children_info;

          if (childrenInfo.length > 0) {
            for (let i = 0; i < childrenInfo.length; i++) {
              this.editForm.parent_bind.push({
                name: i + 1 + '',
                student_number: childrenInfo[i].number,
                student_password: '',
                childrenName: childrenInfo[i].name,
                student_flag: true
              })
            }
          } else {
            this.editForm.parent_bind = [{
              name: '1',
              student_number: '',
              student_password: '',
              childrenName: ''
            }]
          }
        } else {
          this.editForm.parent_bind = [{
            name: '1',
            student_number: '',
            student_password: '',
            childrenName: ''
          }]
        }

        this.parentTabIndex = this.editForm.parent_bind.length;
        this.teachTabIndex = this.teacher_bind.length;
      });

      //执行请求，并将回调方法变成config成员以便鉴权过期可以执行
      // ai分析后接口api/user/user_info改api/user/user
      this.$ajax.get('api/user/user', { params: this.infoParam, func: { success: success } })
    },
    /**
     * 获取组织架构数据
     * 2019-5-5 产品要求单级、多级页面合并，不再区分单级、多级
     */
    getOrgData() {
      if (this.$store.state.checkLevel) {
        this.orgParam.direction = 'down'
        this.orgParam.data_type = 'manage_tree'
        this.orgParam.pid = 1
      }
      let success = (data => {
        this.orgData = data.data;
        // console.log(JSON.parse(JSON.stringify(data.data)),10086)
        this.$forceUpdate();//强制渲染

        // if (this.user_multistage === true) {
        this.studentData = data.data;
        this.editForm.org_id = this.orgData[0].id;
        this.studentItem();
        // }
      });
      if (this.$store.state.checkLevel) {
        this.$ajax.get('api/newlevel/platform_org', { params: this.orgParam, func: { success: success } })
      } else {
        this.$ajax.get('api/org/org', { params: this.orgParam, func: { success: success } })
      }
    },
    getSubjectData() {   // 获取科目信息
      let success = (data => {
        this.subjectData = data.data;
        this.initFuncNumFinal++;
      });
      if (this.$store.state.checkLevel) {
        this.$ajax.get('api/newlevel/platform_subject', { params: {}, func: { success: success } })
      } else {
        this.$ajax.get('api/cate/simple_subject', { params: {}, func: { success: success } })
      }
    },
    getRoleData() { // 获取角色权限
      let success = (data => {
        this.roleData = data.data;
        this.initFuncNumFinal++;
      });

      this.$ajax.get('api/user/user_allow_control', { params: this.roleParam, func: { success: success } })
    },
    /**
     * 不同角色权限的交集
     */
    addFormRoleChange(val) {
      if (!is_empty(this.bindTeach)) {
        if (val.length === 0 || (val.includes(4)) || (val.includes(7)) || (val.includes(8)) || (!val.includes(6))) {
          let className = '';
          !is_empty(this.baseTeacherClass) && this.baseTeacherClass.forEach((item, inx1) => {
            className += inx1 !== 0 ? ` 和 【${item.rename}】` : '' + `【${item.rename}】`;
          })

          this.editForm.role_id = this.bindTeach;
          this.bindTeach = [];

          this.$message.warning(`由于${this.editForm.name}是${className}的班主任，如要取消该用户教师身份，请去班级管理中更改绑定班级的班主任`);

          return false;
        }
      }

      if (val.length === 0) {
        this.isTeacher = false;
        this.isStudent = false;
        this.isParent = false;

        return false;
      }

      let curRoleId = parseInt(val[val.length - 1]);
      switch (curRoleId) {
        case 1:
        case 2:
        case 3: // 管理员与学生和游客角色无交集
          if (val.length > 1) {
            this.editForm.role_id = val.filter(item => {
              return item !== 7 && item !== 4
            })
          }
          break;
        case 4: // 学生只与自建角色有交集
          if (val.length > 1) {
            this.editForm.role_id = val.filter(item => {
              return item === 4 || item >= 9
            })
          }
          break;
        case 5: // 家长与管理员、教师、自建角色有交集
          if (val.length > 1) {
            this.editForm.role_id = val.filter(item => {
              return item <= 3 || item === 5 || item === 6 || item >= 9
            })
          }
          break;
        case 6: // 教师与管理员、家长、自建角色有交集
          if (val.length > 1) {
            this.editForm.role_id = val.filter(item => {
              return item <= 3 || item === 5 || item === 6 || item >= 9
            })
          }
          break;
        case 7: // 游客跟其他角色互斥
          this.editForm.role_id = [curRoleId];
          break;
        case 8: // 教研员跟管理员和自建角色有交集，与其他角色无交集
          if (val.length > 1) {
            this.editForm.role_id = val.filter(item => {
              return item <= 3 || item >= 8
            })
          }
          break;
        default: // 自建角色与游客无交集
          if (val.length > 1) {
            this.editForm.role_id = val.filter(item => {
              return item !== 7
            })
          }
      }

      this.isStudent = this.editForm.role_id.includes(4);
      this.isParent = this.editForm.role_id.includes(5);
      this.isTeacher = this.editForm.role_id.includes(6);

      this.isShowSubject();
      this.getManagerFalg()
    },
    getManagerFalg() {
      let success = (res) => {
        this.isManageFlag = res.data == true ? true : false;
        if (this.editForm.password) {
          this.$refs.editForm.validateField('password');
        }
      }
      let params = {
        role_id: this.editForm.role_id
      }
      this.$ajax.get("api/user/checkManager", {
        params,
        func: { success },
      });
    },
    // 保存修改数据
    submitForm() {

      this.$refs.editForm.validate(valid => {
        if (valid) {
          // 验证通过做点什么操作
          this.saveUser();
        } else {
          return false
        }
      })
    },
    // 检查验证码是否正确
    saveUser() {
      const success = (res => {

        this.submit();
        // this.$message.success(res.msg);
      })
      const fail = (res => {
        this.$message.error(res.msg);
      })
      const checkParams = {
        id: this.$g.user_id,
        password: this.editForm.user_password
      }
      this.$ajax.get("api/user/check_user_by_id", { params: checkParams, func: { success, fail } });
    },
    /**
     * 保存修改的页面数据
     * 2019-5-5 产品要求单级、多级页面合并，不再区分单级、多级
     */
    submit() {

      let success = (data => {
        this.$message.success(data.msg);
        if (this.editForm.newpassword) {
          let params = {
            type: "edit_login",
            token: sessionStorage.getItem('token'),
            terminal_type: 1,
            delete_userid: this.editForm.id,
          }
          this.longSocket.send(JSON.stringify(params));
        }
        setTimeout(() => {
          if (this.$route.hash) {
            this.$router.push('/user/class/class-management/' + this.$route.hash.split('#')[1]);
          } else {
            this.$router.push('/user/user/platform-user/');
          }
        }, 1000)
      })
      let fail = (res => {
        let idArr = [];
        this.roleData.map(x => {
          if (this.editForm.role_id.includes(x.id)) {
            idArr.push(x.base_id === 0 ? x.id : x.base_id)
          }
        })
        this.editForm.role_id = idArr;
        longTimeMessage(this, res, 10000);

      })
      // 选中班级
      if (this.studentSelectOptions.length === 3) {
        this.editForm.student_bind = [];
        this.editForm.student_bind.push({
          student_class_id: this.studentSelectOptions[2],
          student_job_id: this.student_job_id
        })
      } else {
        this.editForm.student_bind = [];
      }

      // 老师角色选中班级
      let teacher_demo = [];
      this.teacher_bind.forEach(item => {
        if (item.teacher_class_id.length === 3) {
          teacher_demo.push({
            teacher_class_id: item.teacher_class_id[2],
            teacher_job_id: item.teacher_job_id,
          })
        }
      });
      this.editForm.teacher_bind = teacher_demo;

      // 家长角色选中子女
      this.editForm.parent_bind.forEach(item => {
        if (item.student_number == '') {
          item.student_number = null;
          item.student_password = null;
          item.childrenName = null;
        }
      })

      if (this.isStudent) {
        this.editForm.study_status = this.study_status;
      } else {
        this.study_status = null;
      }

      let new_time = '00-00-00 00:00:00';
      this.editForm.use_start_time = new_time;
      this.editForm.use_end_time = this.user_time === '1' ? new_time : this.short_time;


      // 角色权限：提交数据，role_id实际是要id，模板checkbox绑定的是base_id，所以此处需要转一下，拿到id
      let idArr = [];
      this.roleData.map(x => {
        if (this.editForm.role_id.includes(x.base_id === 0 ? x.id : x.base_id)) {
          idArr.push(x.id)
        }
      })
      this.editForm.role_id = idArr;

      this.$ajax.put('api/user/user', this.editForm, { func: { success: success, fail: fail } })
    },
    /**
     * websocket 连接，用户被修改后退出登录
     */
    websocketInit() {
      let webSocketURL = "ws://" + this.BASE_URL.split(":")[1] + ":7474";
      this.longSocket = new WebSocket(webSocketURL);

      this.longSocket.onopen = ((res) => {

      });
      this.longSocket.onmessage = (res => { });
      this.longSocket.onclose = (res => { })
    },
    /**
     * 重置编辑页面
     * 2019-5-5 产品要求单级、多级页面合并，不再区分单级、多级
     */
    resetForm() {
      // if (this.user_multistage === true) {17L,H JMUU;L.';

      this.parentTabIndex = 1;
      this.parentEditTabsValue = '1';
      this.teachTabIndex = 1;
      this.teachEditTabsValue = '1';
      // }

      this.$refs.editForm.resetFields()
      this.getInfo();
    },
    cancel() {  // 取消编辑
      if (this.$route.hash) {
        this.$router.push('/user/class/class-management/' + this.$route.hash.split('#')[1]);
      } else {
        this.$router.push('/user/user/platform-user/');
      }
    },
    // 表单验证 start
    validateContent(rule, value, callback) {
      if (value === '') {
        return callback(new Error('请输入真实姓名'));
      } else if (!validateName(value)) {
        return callback(new Error('不能输入空格符号'));
      } else {
        callback()
      }
    },
    validateAccounts(rule, value, callback) {
      if (value === '') {
        return callback(new Error('请输入登录账号'));
      } else if (!validateName(value)) {
        return callback(new Error('不能输入空格符号'));
      } else {
        callback()
      }
    },
    validatePass(rule, value, callback) {
      if (this.editForm.newpassword) {
        this.$refs.editForm.validateField('newpassword');
      }
      callback();
    },
    validateCheckPass(rule, value, callback) {
      if ((value || this.editForm.password) && (value !== this.editForm.password)) {
        // if (value !== this.editForm.password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    },
    validatePwdRole(rule, value, callback) {
      if (value) {
        // 当前用户为管理员
        // 密码长度不得少于8位，由数字、大&小写字母、符号组成（至少4选3）
        let regManager = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d|.*[^\w\s])(?=.*[^\w\s])[^\s]{8,}$|^(?=.*[A-Z])(?=.*[a-z])(?=.*[^\w\s])(?=.*\d)[^\s]{8,}$|^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[^\s]{8,}$|^(?=.*[a-z])(?=.*\d)(?=.*[^\w\s])[^\s]{8,}$|^(?=.*[A-Z])(?=.*\d)(?=.*[^\w\s])[^\s]{8,}$/;
        // 密码长度不得少于8位，由任意数字、字母组合组成
        let regx = /^(?=.*[A-Za-z])(?=.*\d)(?!.*\s)[A-Za-z\d￥!@#$%^&*()_+={}\[\]:;"'<>,.?/~`-]{8,}$/;
        if (this.isManageFlag) {
          if (!regManager.test(value)) {
            callback(new Error("密码不符合规范，密码长度不得少于8位，由数字、大写字母、小写字母、符号组成（至少4选3）"));
          } else {
            callback();
          }
        } else {
          if (!regx.test(value)) {
            callback(new Error("密码不符合规范，密码长度不得少于8位，由任意数字、字母组合组成"));
          } else {
            callback();
          }
        }
      } else {
        callback();
      }
    },
    checkChange(rule, value, callback) {
      if (!isEmpty(value)) {
        return callback(new Error('请选择选项'));
      } else {
        callback()
      }
    },
    validateNumbers(rule, value, callback) {
      if (value === '') {
        callback(new Error('请输入管理员密码'));
      } else {
        callback()
      }
    },
    // 表单验证 end
  },
  destroyed(to, from, next) {
    this.$message.closeAll();
  },
}
</script>
<style lang="scss">
.zh-edit-platform-user {
  .el-form-item__error {
    width: 550px;
  }

  .user-time {
    .el-form-item__content .el-radio-group {
      width: 100%;

      .el-radio {
        line-height: 2;
        width: 100%;
      }

      .el-radio:last-child {
        display: flex;
        align-items: center;
        justify-content: flex-start;
        margin-left: 0;
      }
    }
  }

  .edit-from-width {
    width: 400px;
  }

  .tabs-head-title {
    .el-tabs__header {
      display: inline-block;
    }
  }

  .el-tabs__header {
    display: inline-block;
  }

  .tabs-close {
    .el-icon-close {
      visibility: hidden;
      transition: none
    }
  }

  .el-cascader--small {
    width: 300px;

    .el-cascader__label {
      font-family: "Simsun";
    }
  }

  .form-title {
    border-left: 5px solid #4CC3C3;
    margin-left: -20px;
    padding-left: 7px;
    text-align: left;
  }

  .submit-button {
    padding-top: 50px;
  }
}
</style>
